<script setup>
import { reactive } from 'vue';
import { Dialog } from '@varlet/ui'
import '@varlet/ui/es/dialog/style/index.js';
import { login } from '@/api';
import { setToken } from '@/utils/store';
import { useMessage } from 'naive-ui';
import { useRouter } from 'vue-router';
const router = useRouter();

const message = useMessage();

const formData = reactive({
  key: '',
  password: ''
});

// 提交表单
const Submit = async ()=> {
  if(formData.key.length < 3) {
    return message.error('请输入正确！');
  }
  let r = await login(formData.key, formData.password);
  console.log(r)
  if (r.code == 200) {
    let isToken = false;
    if (JSON.stringify(r.data.token) != '') {
      isToken = setToken(r.data.token);
    }
    if (isToken) {
      return Dialog({
        title: '登录成功 √',
        message: `欢迎回来！是否进入首页？`,
        cancelButton: false,
        closeOnClickOverlay: false,
        onClosed: ()=>{
          router.push('/home');
        }
      });
    } else {
      return message.warning('系统出现异常！');
    }
  } else {
    return message.warning(r.msg);
  }
}
</script>
<template>
    <div class="from">
      <var-space direction="column" :size="[14, 0]">
          <n-input maxlength="30" v-model:value="formData.key" 
            type="text" placeholder="请输入卡密" :autofocus="true"/>
          <n-input maxlength="30" v-model:value="formData.password"
            type="password" placeholder="请输入密码" />
          <var-button block type="primary" size="large" @click="Submit">
            登录
          </var-button>
      </var-space>
    </div>
</template>
<style scoped>
.from {
  padding-top: 20px;
}
</style>